package pilgun.Multithread.BigInteger;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class BigIntegerTry implements Runnable {
	private static int RUNS_NUM = 10;
	private static int THREADS_NUM = 10;
	private static List<BigInteger> bigList = new ArrayList<BigInteger>();
	
	public static boolean isAllDone(List<Future> results){
		for (Future f: results){
			if (!f.isDone()){
				return false;
			}
		}
		
		return true;
	}
	
	public void run() {
		for (int i = 0; i < RUNS_NUM; i++) {
			BigInteger next = BigIntegerGenerator.BigIntegerNext();
			System.out.println(Thread.currentThread().getName() + "  "+ next);
			bigList.add(next);
		}
	}

	public static void main(String[] args) {
		
		if (THREADS_NUM<=0 || RUNS_NUM<=0){
			return;
		}
		ExecutorService pool = Executors.newFixedThreadPool(THREADS_NUM);
		List<Future> results = new ArrayList<Future>();
		for (int i = 0;i<THREADS_NUM;i++){
			 results.add(pool.submit(new BigIntegerTry()));
		}		
		pool.shutdown();
		while (!isAllDone(results)){
		}
		Object[] bigArray = bigList.toArray();
		Arrays.sort(bigArray);
		BigInteger[] singleThreadArray = new BigInteger[THREADS_NUM*RUNS_NUM];
		singleThreadArray[0] = BigInteger.valueOf(2);
		for (int i = 1;i<THREADS_NUM*RUNS_NUM;i++){
			singleThreadArray[i] = singleThreadArray[i-1].multiply(BigInteger.valueOf(2));
		}
		System.out.println(Arrays.toString(bigArray));
		System.out.println(Arrays.toString(singleThreadArray));
		if (Arrays.equals(bigArray, singleThreadArray)){
			System.out.println("Arrays are equal!");
		}else{
			System.out.println("Arrays are less equal, than they could be...");
		}
		
	}
}